<?php
namespace app\extend\kline;

class Baidu
{
    protected static $http = 'https://finance.pae.baidu.com/vapi/v1';

    /**
     * 获取金额
     * @param $code
     * @return array
     */
    public static function getPrice($code)
    {
        $api = self::$http . "/getquotation?group=huilv_minute&need_reverse_real=1&code=".$code."&finClientType=pc";

        $result = curlGet($api);

        if(!isset($result['data']['Result']['pankouinfos']['list']) || empty($result['data']['Result']['pankouinfos']['list'])){
            return [
                'price' => 0,
                'open' => 0,
                'close' => 0,
                'high' => 0,
                'low' => 0
            ];
        } else {
            return [
                'price' => $result['data']['Result']['cur']['price'],
                'open' => $result['data']['Result']['pankouinfos']['list'][0]['value'],
                'close' => $result['data']['Result']['pankouinfos']['list'][3]['value'],
                'high' => $result['data']['Result']['pankouinfos']['list'][1]['value'],
                'low' => $result['data']['Result']['pankouinfos']['list'][4]['value']
            ];
        }


    }

    /**
     * 获取
     * @param $code
     * @param $interval
     * @param $num
     * @return array|false
     */
    public static function getKline($code,$interval,$num)
    {
        $timeArr = ['1'=>'1min', '5'=>'min5', '30'=>'min30', '60'=>'min60', 'd'=>'day','m' => 'month'];

        $api = self::$http."/getquotation?group=huilv_kline&ktype=".$timeArr[$interval]."&code=".$code."&finClientType=pc&count=".$num;

        $result = curlGet($api);

        $data = self::_getFormatLine($result['data']['Result']['newMarketData']['marketData']);

        return $data;
    }

    /**
     * 获取格式化K线数据
     * @param $data
     * @return array|false
     */
    private static function _getFormatLine($data) {

        $result = [];

        if (empty($data)){
            return false;
        }

        $arr = explode(';',$data);
        foreach ($arr as $val) {
            $tmpArr = explode(',',$val);

            $result[] = [
                'timestamp' => $tmpArr[0] * 1000,
                'open' => $tmpArr[2],
                'close' => $tmpArr[3],
                'high' => $tmpArr[4],
                'low' => $tmpArr[5],
                'volume' => $tmpArr[8]
            ];
        }

        return $result;
    }
}